<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ResponseException;
use App\Models\Goods;
use App\Models\GoodsBrand;
use App\Models\GoodsCategory;
use App\Models\GoodsSpec;
use App\Models\SpecValue;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SearchController extends Controller
{
    /**
     * 产品搜索页面(已停用)
     * User: ihome
     * @param Request $request
     * @throws ResponseException
     */
    public function searchGoods(Request $request)
    {
        $keyword = $request->input('keyword');

        if ( ! $keyword) {
            throw new ResponseException(400, '缺少搜索关键词');
        }

        $goodsList = Goods::query()
            ->select('id', 'thumb', 'goods_name', 'price')
            ->where([
                'status' => 1,
                ['goods_name', 'like', "%$keyword%"]
            ])->orderBy('created_at', 'desc')->paginate(10);

        throw new ResponseException(200, 'ok', $goodsList);
    }


    /**
     * 搜索商品
     * User: Clannad ~ ☆
     * @param Request $request
     * @throws ResponseException
     */
    public function Search(Request $request)
    {
        //取数据
        $category_id = $request->input('category_id');

        if ( ! $category_id) {
            throw new ResponseException(400, '请择分类搜索');
        }

        //判断分类是顶级还是二级
        $categoryList = [];
        $category_ids = []; //分类下的子分类

        $category = GoodsCategory::query()->select('id', 'category_name', 'pid')->where([
            'id'      => $category_id,
            'is_show' => 1
        ])->first();

        if ( ! $category) {
            throw new ResponseException(404, '分类不存在');
        }

        //子分类 就取出当前上级分类的东西
        if ($category->pid != 0) {
            $category_ids = getChildIds('goods_category', $category->pid, ['is_show' => 1]);
        } else {
            //顶级分类就直接取下面的子分类
            $category_ids = getChildIds('goods_category', $category_id, ['is_show' => 1]);
        }

//        $category_ids[] = $category_id;//把自己也加入进去

        $categoryList = GoodsCategory::query()->select('id', 'category_name')->whereIn('id', $category_ids)->get()->toArray();


        //当前分类下的所有商品id 用于计算筛选条件 有分类id就计算分类id的 没有分类id 就统计搜索条件的

        //商品品牌
        $brandList = [];

        $where = [
            'status' => 1,
        ];

        $newQuery = Goods::query()->select('brand_id', 'id', 'goods_name', 'thumb', 'price');

        if ($category->pid == 0) {
            $newQuery->whereIn('category_id', $category_ids);
            $newQuery->where($where);
        } else {
            $where['category_id'] = $category_id;
            $newQuery->where($where);
        }
        //全部商品，这里用于筛选商品品牌和可选筛选属性
        $goods = $newQuery->orderBy('created_at', 'desc')->get()->toArray();

        //取出第一页的商品条数
        $goodsList = $newQuery->orderBy('created_at', 'desc')->paginate(10);

        //因为考虑到商城品牌的数量 这里最多取出10个
        $brand_ids = array_column($goods, 'brand_id');
        $brandList = GoodsBrand::query()->select('id', 'brand_name')
            ->where('is_show', 1)
            ->whereIn('id', $brand_ids)
            ->limit(10)
            ->get()->toArray();

        //根据商品id 去拿筛选条件
        $goods_ids   = array_column($goods, 'id');
        $filter_data = $this->getFilterDataByGoods($goods_ids);

        $data = [
            'goodsList'        => $goodsList,
            'categoryList'     => $categoryList,
            'brandList'        => $brandList,
            'priceList'        => $filter_data['priceList'],
            'filter_attr_data' => $filter_data['filter_attr_data'],
        ];

        throw new ResponseException(200, 'ok', $data);

    }

    /**
     * 根据商品id计算筛选条件
     * User: ihome
     * @param $goods_ids
     */
    public function getFilterDataByGoods($goods_ids)
    {
        //计算价格阶梯
        $priceBetween = Goods::query()
                        ->select(\DB::raw('MAX(price) as max_price,MIN(price) as min_price'))
                        ->whereIn('id', $goods_ids)
                        ->where('status',1)
                        ->first()
                        ->toArray();

        $min_price = $priceBetween['min_price'];
        $max_price = $priceBetween['max_price'];

        $priceColumn   = [];//价格分段数据
        $priceColCount = 0; //价格分段数量

        //如果最高价和最低价相差小于100 则不分段
        $difference = $max_price - $min_price; //最大最小价格差值
        if ($difference > 5000) {
            $priceColCount = 5;
        } elseif ($difference > 3000) {
            $priceColCount = 4;
        } elseif ($difference > 1000) {
            $priceColCount = 3;
        } elseif ($difference > 600) {
            $priceColCount = 2;
        } elseif ($difference < 100 && $priceColCount != 0) {
            $priceColCount = 1;
        }else if($difference == 0) {
            $priceColCount = 0;
        }

        //如果只分了1段
        if ($priceColCount == 1) {
            if ($min_price < 100) {
                $betweenMinPrice = ceil($min_price / 100) * 10;
            } else {
                $betweenMinPrice = floor($min_price / 100) * 100;
            }

            if ($max_price < 100) {
                $betweenMaxPrice = 99;  //小于100  就直接取值100
            } else {
                $betweenMaxPrice = floor(($max_price) / 100) * 100;
            }

            $priceColumn[] = [$betweenMinPrice, $betweenMaxPrice];
        } else if($priceColCount > 1){
            $between = ($max_price - $min_price) / $priceColCount;

            //计算每一个差价范围
            for ($i = 0; $i < $priceColCount; $i++) {
                //查询当前价格范围是否有商品 没有的话就跳过
                if ($min_price < 100) {
                    $betweenMinPrice = ceil($min_price / 100) * 10;
                } else {
                    $betweenMinPrice = floor($min_price / 100) * 100;
                }

                $betweenMaxPrice = floor(($min_price + $between) / 100) * 100;

                //最后一段
                if ($i == $priceColCount - 1) {
                    $betweenMaxPrice = $min_price + $between;
                    //获取长度
                    $len = strlen($betweenMaxPrice);
                    //获取第一个数
                    $first = substr($betweenMaxPrice,0,1);

                    $betweenMaxPrice = str_pad($first + 1,$len,0) - 1;

                    $priceColumn[] = [$betweenMinPrice, $betweenMaxPrice];
                } else {
                    //非最后一段价格
                    $priceColumn[] = [$betweenMinPrice, $betweenMaxPrice - 1];
                }
                $min_price += $between;
            }
        }

        //计算商品筛选属性
        $filter_attr_data = GoodsSpec::query()
            ->select('spec.spec_name', 'spec_id', \DB::raw('GROUP_CONCAT(distinct spec_value_id) as value_ids'))
            ->leftJoin('spec', 'goods_spec.spec_id', '=', 'spec.id')
            ->whereIn('goods_id', $goods_ids)
            ->groupBy('spec_id')
            ->get()->toArray();


        foreach ($filter_attr_data as $k => $v) {
            $spec_value_ids                    = explode(',', $v['value_ids']);
            $filter_attr_data[$k]['spec_item'] = SpecValue::query()->select('id', 'value')
                                                ->whereIn('id', $spec_value_ids)
                                                ->get()->toArray();
        }

        $filter_data = [
            'priceList'        => $priceColumn,
            'filter_attr_data' => $filter_attr_data
        ];

        return $filter_data;
    }

    /**
     * 关键词搜索
     * User: Clannad ~ ☆
     * Date: 2020/2/23 0023 12:08
     * @param Request $request
     * @throws ResponseException
     */
    public function keyWordSearch(Request $request)
    {
        $keyword = $request->input('keyword');

        $where = [
            'status'=>1
        ];

        if ($keyword) {
            $where[] = [
                'goods_name', 'like', "%$keyword%"
            ];
        }else{
            throw new ResponseException(400,'请输入关键词搜索');
        }

        //根据关键词搜索出商品
        $goods = Goods::query()->select('id','brand_id','category_id')
                ->where($where)
                ->orderBy('sales_num','desc')
                ->get()->toArray();

        if(!$goods){
            throw new ResponseException(400,'没有找到符合条件的商品');
        }

        //取第一件商品所在分类进行分类的筛选(原来的方式)
        /*$firstGoods = $goods['0'];

        $category = GoodsCategory::query()->select('id','pid')->where('id',$firstGoods['category_id'])->first();

        $pid = $category['pid'];

        if($pid != 0){
            $childCateId = getChildIds('goods_category',$pid,['is_show'=>1]);
        }else{
            $childCateId = getChildIds('goods_category',$category['id'],['is_show'=>1]);
        }*/

        $childCateId = array_column($goods,'category_id');

        $categoryList = GoodsCategory::query()
            ->select('id','category_name')
            ->where('is_show',1)
            ->whereIn('id',$childCateId)->get()->toArray();

        //根据关键词搜索出来的商品进行品牌的筛选
        $brand_ids = array_column($goods,'brand_id');

        $brandList = GoodsBrand::query()->select('id', 'brand_name')
                    ->where('is_show', 1)
                    ->whereIn('id', $brand_ids)
                    ->limit(10)
                    ->get()->toArray();

        //把分类搜索出来的商品进行属性的筛选

        $goodsList = Goods::query()
                    ->select('id','goods_name','thumb','price')
                    ->where($where)
                    ->orderBy('sales_num','desc')
                    ->paginate(10);

        $goods_ids   = array_column($goods, 'id');
        $filter_data = $this->getFilterDataByGoods($goods_ids);

        $data = [
            'goodsList'        => $goodsList,
            'categoryList'     => $categoryList,
            'brandList'        => $brandList,
            'priceList'        => $filter_data['priceList'],
            'filter_attr_data' => $filter_data['filter_attr_data'],
        ];

        throw new ResponseException(200, 'ok', $data);
        //根据分页取商品
    }

    /**
     * 根据搜索条件过滤商品
     * User: ihome
     */
    public function filterGoods(Request $request)
    {
        //取分类
        $category_id = $request->input('category_id');
        $brand_id    = $request->input('brand_id');
        $price       = $request->input('price');
        $filter_attr = $request->input('filter_attr');
        $orderBy     = $request->input('orderBy');
        $keyword     = $request->input('keyword');

        $query = Goods::query()->select('id', 'goods_name', 'thumb', 'price');

        $where = [
            'status'=>1
        ];

        if ($category_id) {
            $category = GoodsCategory::query()->where(['id' => $category_id])->first();

            if ($category->pid != 0) {
                $where['category_id'] = $category_id;
            } else {
                //是顶级分类的话，要取子分类
                $childCateId   = getChildIds('goods_category', $category_id, ['is_show' => 1]);
                $childCateId[] = $category_id;

                $query->whereIn('category_id', $childCateId);
            }
        }

        $brand_id ? $where['brand_id'] = $brand_id : '';

        if ($price) {
            $between = explode(',', $price);
            $query->whereBetween('price', $between);
        }

        if ($keyword) {
            $where[] = [
                'goods_name', 'like', "%$keyword%"
            ];
        }

        switch ($orderBy) {
            case '0':
                $query->orderBy('price', 'asc');
                break;
            case '1':
                $query->orderBy('price', 'desc');
                break;
            case '2': //按销量
                $query->orderBy('sales_num', 'desc');
                break;
            case '3': //按时间
                $query->orderBy('created_at', 'desc');
                break;

            //默认按时间
            default:
                $query->orderBy('created_at', 'desc');
                break;
        }

        $filterCount = 0;
        if ($filter_attr) {
            $goods_attrs = explode(',', $filter_attr);

            $goodsIdsArr = null;

            foreach ($goods_attrs as $k => $v) {
                if ($v != '0') {
                    //筛选条件的个数，如果是0 表示没有筛选属性
                    $filterCount++;
                    //根据每一个属性进行取数据
                    $goods_ids = GoodsSpec::query()
                                ->select(\DB::raw('GROUP_CONCAT(distinct goods_id) as goods_ids '))
                                ->where('spec_value_id', $v)
                                ->first();

                    if($goods_ids){
                        $goods_ids = $goods_ids->toArray();
                    }else{
                        $goods_ids = [];
                    }

                    if ( ! $goodsIdsArr) {
                        $goodsIdsArr = explode(',',$goods_ids['goods_ids']);
                    } else {
                        $goods_ids = explode(',',$goods_ids['goods_ids']);
                        // 2个2个取交集
                        $goodsIdsArr =  array_intersect($goodsIdsArr,$goods_ids);

                        //如果都取不到交集了，说明已经没有合适的属性了
                        if(!$goodsIdsArr){
                            break;
                        }
                    }
                }
            }

            if($filterCount){
                if($goodsIdsArr){
                    $query->whereIn('id',$goodsIdsArr);
                }else{
                    $where['id'] = 0; //没有数据的话，就直接让它取不到数据就可以了。
                }
            }

        }

        //开始取数据
        $goodsList = $query->where($where)->paginate(10);

        throw new ResponseException(200,'ok',$goodsList);

    }

}
